package com.livegoods.rabbitmq.service.impl;

import com.livegoods.pojo.House;
import com.livegoods.pojo.Order;
import com.livegoods.rabbitmq.dao.HouseDao4MongoDB;
import com.livegoods.rabbitmq.dao.HouseDao4Redis;
import com.livegoods.rabbitmq.dao.OrderDao;
import com.livegoods.rabbitmq.service.BuyactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class BuyactionServiceImpl implements BuyactionService {


    @Autowired
    private HouseDao4Redis houseDao4Redis;

    @Autowired
    private HouseDao4MongoDB houseDao4MongoDB;

    @Autowired
    private OrderDao orderDao;

    /**
     *
     * 1, 检查缓存是否存在并且 house 的 rented 是否为 false
     *
     * 2，修改Redis缓存（redis 单线程）
     *
     * 3，修改MongoDB库存
     *
     * 4，下订单
     *
     */

    @Value("${livegoods.redis.house.detail}")
    private String houseKey;

    @Override
    public Boolean buyaction(String houseId, String username) {

        String key = houseKey+houseId;
        System.out.println("key = " + key);
        //获取Redis中房屋信息
        House house = houseDao4Redis.get(key);
        //设置为出租
        house.setRented(true);

        //修改Redis缓存
        boolean result = houseDao4Redis.set(key,house);

        if(result){
            //修改MongoDB房屋的出租状态
            long row = houseDao4MongoDB.updateRented(houseId);
            //下订单
            if(row==1){

                //创建订单对象
                Order order = new Order();
                order.setUsername(username);
                order.setHouseId(houseId);
                order.setTitle(house.getTitle());
                order.setRentType(house.getRentType());
                order.setImg(house.getImgs().get(0));
                order.setPrice(house.getPrice());
                order.setCommentState(0);//默认订单未评论

                //新增订单
                long rows1 = orderDao.insert(order);

                return rows1==1?true:false;
            }else{
                return false;
            }
        }
        return result;
    }
}
